package taskManager.ui;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import taskManager.commonLayer.Task;
import taskManager.dataAccessLayer.TaskDataAccessClass;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.datastore.*;

public class TaskServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	
	public TaskServlet()
	{
		super();
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		UserService userService = UserServiceFactory.getUserService();
		
		PrintWriter out = response.getWriter();
		response.setContentType("text/html");
		response.setHeader("Cache-control", "no-cache, no-store");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Expires", "-1");
		
		TaskDataAccessClass taskDataAccessObject = new TaskDataAccessClass();
		try
		{
			String action = request.getParameter("action");
			
			action = action == null ? "" : action;
			
			if (action.equals("complete"))
			{
				// parameters: id, completed, content
				Task task = new Task();
				String completed = request.getParameter("completed");
				if (ifIsNullOrEmpty(completed))
				{
					out.write("{ \"error\": \"completed didn't passsed for the specific task.\" }");
					return;
				}
				String id = request.getParameter("id");
				if (ifIsNullOrEmpty(id))
				{
					out.write("{ \"error\": \"id didn't passsed for the specific task.\" }");
					return;
				}
				
				task.setCompleted(Boolean.parseBoolean(completed.toString()));
				task.setTaskKey(KeyFactory.stringToKey(id));
				
				taskDataAccessObject.Update(task);
				out.write("{ \"id\": " + KeyFactory.keyToString(task.getTaskKey())
						+ ", \"content\": \"" + task.getContent() + "\", \"userId\" : \""
						+ task.getUserID() + "\", \"completed\"" + "\""
						+ task.getCompleted() + "\"" + "\"}");
			}
			else if (action.equals("delete"))
			{
				String id = request.getParameter("id");
				if (ifIsNullOrEmpty(id))
				{
					out.write("{ \"error\": \"No task is selected.\" }");
					out.close();
					return;
				}
				taskDataAccessObject.Delete(KeyFactory.stringToKey(id));
				out.write("{ \"message\": \"success\", \"key\": \""
						+ KeyFactory.keyToString(KeyFactory.stringToKey(id)) + "\"}");
			}
			else if (action.equals("show"))
			{
				String id = request.getParameter("id");
				if (ifIsNullOrEmpty(id))
				{
					out.write("{ \"error\": \"No task is selected.\" }");
					out.close();
					return;
				}
				
				Task task = taskDataAccessObject.GetTask(KeyFactory.stringToKey(id));
				
				out.write("{ \"id\": " + KeyFactory.keyToString(task.getTaskKey())
						+ ", \"content\": \"" + task.getContent() + "\", \"userId\" : \""
						+ task.getUserID() + "\"}");
			}
			else
			{
				List<Task> userTasks = taskDataAccessObject.GetTasks(userService.getCurrentUser().getUserId());
				out.write("[");
				for (int i = 0; i < userTasks.size(); i++)
				{
					Task task = userTasks.get(i);
					out.write("{\"id\": \"" + KeyFactory.keyToString(task.getTaskKey())
							+ "\",\"content\" :\"" + task.getContent()
							+ "\", \"completed\" : " + task.isCompleted()
							+ ", \"deleted\" : " + task.isDeleted() + "}");
					if (i + 1 < userTasks.size())
					{
						out.write(",");
					}
				}
				out.write("]");
			}
		}
		finally
		{
			out.close();
		}
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		TaskDataAccessClass taskDataAccessObject = new TaskDataAccessClass();
		PrintWriter out = response.getWriter();
		// parameters: completed, content
		UserService us = UserServiceFactory.getUserService();
		
		Task task = new Task();
		task.setCompleted(false);
		String content = request.getParameter("content");
		if (ifIsNullOrEmpty(content))
		{
			out.write("{ \"error\": \"content can't be empty!\" }");
			return;
		}
		
		task.setContent(request.getParameter("content").toString());
		
		task.setUserID(us.getCurrentUser().getUserId());
		
		Key taskKey = taskDataAccessObject.Insert(task);
		out.write("{\"id\": \"" + KeyFactory.keyToString(taskKey)
				+ "\",\"content\" :\"" + task.getContent()
				+ "\", \"completed\" : false}");
	}
	
	private boolean ifIsNullOrEmpty(String str)
	{
		return str == null || str.isEmpty() || str.trim().isEmpty();
	}
}
